package com.youzan.cloud.component.biz.member.service.impl;

import com.alibaba.fastjson.JSON;
import com.youzan.cloud.component.base.util.core.ObjectUtil;
import com.youzan.cloud.component.biz.member.common.util.LogRecordUtil;
import com.youzan.cloud.component.biz.member.common.util.OutResultUtil;
import com.youzan.cloud.component.biz.member.config.MemberLinkerConfiguration;
import com.youzan.cloud.component.biz.member.dal.dataobject.MemberInformation;
import com.youzan.cloud.component.biz.member.dal.mapper.MemberInformationMapper;
import com.youzan.cloud.component.biz.member.dal.mapper.MemberRelationshipMapper;
import com.youzan.cloud.component.biz.member.dto.BaseResult;
import com.youzan.cloud.component.biz.member.dto.LogDTO;
import com.youzan.cloud.component.biz.member.dto.MemberBaseDto;
import com.youzan.cloud.component.biz.member.dto.linker.out.ContactAddressDTO;
import com.youzan.cloud.component.biz.member.dto.linker.out.CustomerProfileDTO;
import com.youzan.cloud.component.biz.member.dto.linker.out.MemberLinkerBaseResult;
import com.youzan.cloud.component.biz.member.dto.linker.out.MemberQueryResult;
import com.youzan.cloud.component.biz.member.youzanopen.api.YzMemberApiService;
import com.youzan.cloud.connect.service.common.domain.BizServiceInfo;
import com.youzan.cloud.connect.service.sdk.ConnectServiceResponse;
import com.youzan.cloud.connect.service.sdk.exception.ConnectServiceCallException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;

/**
 * @author tangsen233
 * @version 1.0
 * @description: ISV主动获取会员信息
 * @date 2021/8/4 10:24
 */
@Service
@Slf4j
public class MemberQueryService extends AbstractService {

    @Autowired
    MemberInformationMapper memberInformationMapper;

    @Autowired
    private MemberLinkerConfiguration memberLinkerConfiguration;

    @Autowired
    LogRecordUtil logRecordUtil;

    @Autowired
    YzMemberApiService yzMemberApiService;

    @Autowired
    MemberRelationshipMapper memberRelationshipMapper;

    @Override
    public LogDTO buildLog(Object inputParam) {
        return null;
    }

    @Override
    public BaseResult handleException(Exception e) {
        return OutResultUtil.fail("组件异常!","500",e);
    }

    @Override
    public BaseResult doBiz(MemberBaseDto memberBaseDto) {
        String yzOpenId = memberBaseDto.getYzOpenId();
        BizServiceInfo memberQueryLinker = memberLinkerConfiguration.getMemberQueryLinker();
        ConnectServiceResponse<MemberLinkerBaseResult> queryMemberResult = null;
        try {
            queryMemberResult = connectServiceCaller.callConnectService(memberQueryLinker.getConnectServiceName(),memberQueryLinker.getTargetSystem(),memberQueryLinker.getTargetSystemVersion(),memberBaseDto.getMemberQueryDto());
        }catch (ConnectServiceCallException e){
            log.error("调用三方会员查询接口失败" + e.getMessage());
            //查询有赞侧信息
            return OutResultUtil.fail(queryMemberResult.getErrMsg(),queryMemberResult.getErrorCode().toString(),queryMemberResult);
        }
        if(queryMemberResult.isSuccess()){
            MemberQueryResult memberQueryResult =  JSON.parseObject(JSON.toJSONString(queryMemberResult.getResponseDTO()), MemberQueryResult.class);
            if(ObjectUtil.isNotNull(memberQueryResult)){
                //记录会员基本信息
                MemberInformation memberInformation = memberInformationMapper.selectByYzOpenId(yzOpenId);
                if(ObjectUtil.isNotNull(memberInformation)){
                    buildInformation(memberInformation,memberQueryResult,memberBaseDto);
                    memberInformationMapper.updateIgnoreNull(memberInformation);
                    //初始化会员等级
                    yzMemberApiService.getMemberLevel(yzOpenId,memberBaseDto.getKdtId(),memberBaseDto);
                    return OutResultUtil.success(memberQueryResult);
                }
                return OutResultUtil.fail("会员信息不存在","500",null);
            }
        }
        return OutResultUtil.fail("调用会员查询连接器异常",queryMemberResult.getErrorCode().toString(),null);
    }

    private CustomerProfileDTO buildReturnData(MemberInformation memberInformation){
        CustomerProfileDTO customerProfileDTO = new CustomerProfileDTO();
        customerProfileDTO.setName(memberInformation.getSecondName());
        customerProfileDTO.setBirthday(memberInformation.getBirthday() );
        customerProfileDTO.setGender( Short.valueOf( memberInformation.getGender()));
        //填充有赞方数据
        customerProfileDTO.setIsMember(true);
        ContactAddressDTO contactAddressDTO = new ContactAddressDTO();
        contactAddressDTO.setAreaCode(memberInformation.getAreaCode()==null?null:memberInformation.getAreaCode().toString());
        contactAddressDTO.setAddress(memberInformation.getAddress());
        customerProfileDTO.setContactAddressDTO(contactAddressDTO);
        customerProfileDTO.setLatestAvatar(memberInformation.getLatestAvatar());
        customerProfileDTO.setLatestNickName(memberInformation.getLatestNickName());
        return customerProfileDTO;
    }


    public void buildInformation(MemberInformation memberInformation,MemberQueryResult memberQueryResult,MemberBaseDto memberBaseDto){
        memberInformation.setGender(memberQueryResult.getGender()==null?memberInformation.getGender():memberQueryResult.getGender());
        memberInformation.setKdtid(Long.valueOf(memberBaseDto.getKdtId()));
        memberInformation.setLatestAvatar(memberQueryResult.getLatestAvatar()==null?memberInformation.getLatestAvatar():memberQueryResult.getLatestAvatar());
        memberInformation.setYzOpenid(memberBaseDto.getYzOpenId());
        memberInformation.setSecondName(memberQueryResult.getLatestNickName()==null?memberInformation.getSecondName():memberQueryResult.getLatestNickName());
        memberInformation.setLatestNickName(memberQueryResult.getLatestNickName()==null?memberInformation.getLatestNickName():memberQueryResult.getLatestNickName());
        memberInformation.setGrade(memberQueryResult.getGradeId()==null?memberInformation.getGrade():memberQueryResult.getGradeId());
        memberInformation.setAge(memberQueryResult.getAge()==null?null:memberQueryResult.getAge());
        memberInformation.setFirstName(memberQueryResult.getFirstName()==null?null:memberQueryResult.getFirstName());
        memberInformation.setBirthday(memberQueryResult.getBirthday()==null?memberInformation.getBirthday():memberQueryResult.getBirthday());
        memberInformation.setEmail(memberQueryResult.getEmail()==null?null:memberQueryResult.getEmail());
        memberInformation.setUpdateTime(new Date());
        memberInformation.setThirdAccount(memberQueryResult.getThirdAccount()==null?null:memberQueryResult.getThirdAccount());
        memberInformation.setThirdAccountType(memberQueryResult.getThirdAccountType()==null?"1":memberQueryResult.getThirdAccountType());
        memberInformation.setAreaCode(memberInformation.getAreaCode());
        memberInformation.setAddress(memberInformation.getAddress());

    }
}